package com.lingxu.api.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Clob;
import java.util.zip.DataFormatException;

/**
 * @author
 */
@Slf4j
public class ReflectUtil {

    public static void setObjFieldVal(Object obj, String fieldName, Object value) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            if(null!=value&&StringUtils.isNotEmpty(value.toString())){
                if(field.getType().getName().equals("java.util.Date") ){
                    field.set(obj, DateUtils.getDate(value.toString()));
                }else if(field.getType().getName().equals("java.lang.Integer")){
                    field.set(obj, Integer.parseInt(value.toString()));
                }else if(field.getType().getName().equals("java.lang.Long")){
                    field.set(obj, Long.parseLong(value.toString()));
                }else if (field.getType().getName().equals("java.math.BigDecimal")){
                    field.set(obj, new BigDecimal(value.toString()));
                }else if(field.getType().getName().equals("java.lang.Double")){
                    field.set(obj, Double.parseDouble(value.toString()));
                }
//                else if(field.getType().getName().equals("java.sql.Clob")) {
//                    field.set(obj, new Clob(value.toString()));
//                }
                else{
                    field.set(obj, String.valueOf(value));
                }
            }

        } catch (NoSuchFieldException e) {
            log.error("error while set obj field value", e);
        } catch (IllegalAccessException e1) {
            log.error("error while set obj field value", e1);
        }catch (DataFormatException e2){
            log.error("error while set obj field value", e2);
        }catch (Exception e3){
            log.error("error while set obj field value", e3);
        }
    }

    public static String getObjFieldVal(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return (String) field.get(obj);
        } catch (NoSuchFieldException e) {
            log.error("error while set obj field value", e);
        } catch (IllegalAccessException e1) {
            log.error("error while set obj field value", e1);
        }
        return null;
    }

    public static void main(String[] args) {
//        EntryAndExit entryAndExit = new EntryAndExit();
////        2009-09-28-11.52.33.235871
//        ReflectUtil.setObjFieldVal(entryAndExit, "transitTime", "2009-09-28 11.52.33");
//        System.out.println(DateUtils.buildDate("2009-09-28-11.52.33.235871","yyyy-MM-dd HH:mm:ss"));
    }
}

